package com.agile.leetcode.concurrent.thread;

import java.util.concurrent.TimeUnit;

/**
 * @Author ChenZhangKun
 * @Date 2020/11/30 9:13
 */
public class ThreadDemo {
    public static void main(String[] args) {
        // ① 判断当前线程是否被中断
        System.out.println("Main thread is interrupted? " + Thread.interrupted());
        // ② 中断当前线程
        Thread.currentThread().interrupt();
        // ③ 判断当前线程是否已经被中断
        System.out.println("Main thread is interrupted? " + Thread.currentThread().isInterrupted());
        try {
            // ④ 当前线程执行可中断方法 TimeUnit.MINUTES.sleep(1);
        } catch (Exception ex) {
            // ⑤ 捕获中断信号
            System.out.println("I will be interrupted still.");
        }
    }
}

class ThreadDemo_1 {
    public static void main(String[] args) throws InterruptedException {
        Thread thread=new Thread(()->{
           while (true){
               Thread thread1=null;
               try {
                   thread1 = Thread.currentThread();

                   TimeUnit.SECONDS.sleep(5);

               }catch (InterruptedException ex){
                   // 捕获到了异常后会清除打断标记
                   System.out.println("线程被打断了"+thread1.isInterrupted());
               }
           }
        });
        thread.setDaemon(true);
        thread.start();
        TimeUnit.SECONDS.sleep(2);
        System.out.println("线程被打断了吗"+thread.isInterrupted());
        // 打断线程
        thread.interrupt();
        System.out.println(thread.isInterrupted());
    }
}
